package com.teaching.management.controller.api;

import com.teaching.management.entity.CourseSelection;
import com.teaching.management.entity.Teacher;
import com.teaching.management.entity.User;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.repository.CourseSelectionRepository;
import com.teaching.management.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;

/**
 * 教师成绩管理REST API
 */
@RestController
@RequestMapping("/teacher/grade")
public class TeacherGradeRestController {

    @Autowired
    private CourseSelectionRepository courseSelectionRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private TeacherService teacherService;

    /**
     * 保存成绩
     */
    @PostMapping("/save")
    public ResponseEntity<?> saveGrade(@RequestBody Map<String, Object> gradeData, HttpSession session) {
        // 验证用户是否是教师
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("教师信息不存在");
        }

        // 获取成绩记录ID和分数
        Integer gradeId = null;
        BigDecimal score = null;

        try {
            gradeId = Integer.parseInt(gradeData.get("gradeId").toString());
            if (gradeData.get("score") != null) {
                score = new BigDecimal(gradeData.get("score").toString());
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数格式错误");
        }

        // 检查选课记录是否存在
        Optional<CourseSelection> selectionOpt = courseSelectionRepository.findById(gradeId);
        if (!selectionOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("成绩记录不存在");
        }

        CourseSelection selection = selectionOpt.get();

        // 检查课程是否属于该教师
        String courseId = selection.getCourseId();
        courseRepository.findById(courseId).ifPresent(course -> {
            if (!course.getTeacherId().equals(teacher.getTeacherId())) {
                throw new RuntimeException("无权修改其他教师的课程成绩");
            }
        });

        // 更新成绩
        selection.setScore(score);
        CourseSelection updated = courseSelectionRepository.save(selection);

        return ResponseEntity.ok(updated);
    }
}